<template>
  <div class="supervisor-dashboard">
    <el-card title="Supervisor Console" class="dashboard-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>Supervisor Console</span>
          <div class="header-actions">
            <el-button type="primary" class="refresh-button" @click="fetchDashboardData" :loading="loading">
              <el-icon><Refresh /></el-icon>
              Refresh Data
            </el-button>
          </div>
        </div>
      </template>

      <el-tabs type="border-card" v-model="activeTab">
        <el-tab-pane label="Student List" name="students">
          <el-table :data="paginatedStudents" style="width: 100%">
            <el-table-column prop="studentName" label="Name" />
            <el-table-column prop="projectTitle" label="Project" />
            <el-table-column label="Status">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.projectStatus)">
                  {{ scope.row.projectStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="Actions">
              <template #default="scope">
                <el-button size="small" @click="viewStudentDetails(scope.row)">View</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination 
              layout="prev, pager, next" 
              :total="studentsWithProgress.length"
              :page-size="pagination.pageSize" 
              :current-page="currentPage"
              @current-change="handlePageChange"
            />
          </div>
          <el-empty v-if="!studentsWithProgress || studentsWithProgress.length === 0"
                   description="No student project progress data available"></el-empty>
        </el-tab-pane>
        <el-tab-pane label="Recent Activities" name="recent">
          <div class="activity-list">
            <el-card v-for="(activity, index) in dashboardData.recentActivities" :key="index" 
                    class="activity-item" shadow="hover">
              <div class="activity-title">{{ activity.title }}</div>
              <div class="activity-description">{{ activity.description }}</div>
              <div class="activity-time">{{ activity.time }}</div>
            </el-card>
            <el-empty v-if="!dashboardData.recentActivities || dashboardData.recentActivities.length === 0"
                     description="No activity records"></el-empty>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElCard, ElButton, ElIcon, ElTabs, ElTabPane,
  ElTable, ElTableColumn, ElTag, ElPagination, ElEmpty, ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import axiosInstance from '../../utils/axios'; // Import the configured axios instance
import { useUserStore } from '../../stores/user'; // Import the user store

// Router instance
const router = useRouter();
// User store
const userStore = useUserStore();

// Currently active tab
const activeTab = ref('students');

// Dashboard data
const dashboardData = ref({
  studentCount: 0,
  activeToday: 0,
  pendingTasks: 0,
  weeklyEvents: 0,
  studentProjectProgresses: [],
  recentActivities: []
});

// Loading state
const loading = ref(false);

// Student list configuration
const studentColumns = [
  { title: 'Name', key: 'studentName' },
  { title: 'Project', key: 'projectTitle' },
  { title: 'Status', key: 'projectStatus' },
  { title: 'Actions', key: 'actions' }
];

// Student progress list computed property
const studentsWithProgress = computed(() => {
  // Add debug logs
  console.log('Student progress data:', dashboardData.value.studentProjectProgresses);
  // Ensure each student has a name
  return (dashboardData.value.studentProjectProgresses || []).map(student => {
    if (!student.studentName) {
      console.warn('Found student without name:', student);
      student.studentName = 'Unknown Student';
    }
    return student;
  });
});

// Pagination configuration - controls how many items appear per page
const pagination = {
  pageSize: 5
};

// Current page for pagination - tracks which page the user is currently viewing
const currentPage = ref(1);

// Paginated students list for current page - slices the full data array to show only current page items
const paginatedStudents = computed(() => {
  // Calculate start and end indices based on current page and page size
  const startIndex = (currentPage.value - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  // Return only the items for the current page
  return studentsWithProgress.value.slice(startIndex, endIndex);
});

// Handle pagination page change
function handlePageChange(page) {
  currentPage.value = page;
}

// View student details
function viewStudentDetails(student) {
  console.log('Viewing student project details:', student);
  router.push({
    name: 'SupervisorTasks',
    query: { 
      projectId: student.projectId 
    }
  });
}

// Get dashboard data
async function fetchDashboardData() {
  // Check if the user is logged in
  if (!userStore.isLoggedIn) {
    ElMessage.error('You are not logged in, please login first');
    router.push('/login');
    return;
  }

  // Check if the user has a supervisor role
  if (!userStore.isSupervisor) {
    ElMessage.error('You do not have supervisor privileges to access this page');
    router.push('/');
    return;
  }

  // Reset pagination to first page when refreshing data
  currentPage.value = 1;

  loading.value = true;
  try {
    console.log('Starting request for supervisor dashboard data');

    // Use the configured axios instance
    const response = await axiosInstance.get('/api/dashboard/supervisor/stats');

    console.log('Dashboard data retrieved successfully:', response.data);

    // Check student names
    if (response.data.studentProjectProgresses && response.data.studentProjectProgresses.length > 0) {
      response.data.studentProjectProgresses.forEach(student => {
        console.log(`Username: ${student.username}, Name: ${student.studentName}`);
      });
    }

    dashboardData.value = response.data;
    ElMessage.success('Data updated');
  } catch (error) {
    console.error('Failed to get dashboard data:', error);

    // Detailed error handling
    if (error.response) {
      // The server responded with an error status code
      const status = error.response.status;
      const errorMsg = error.response.data?.message || 'Unknown error';

      if (status === 401) {
        ElMessage.error('Authentication expired, please login again');
        userStore.logout(); // Log out and clear authentication state
        router.push('/login');
      } else if (status === 403) {
        ElMessage.error('Insufficient privileges, please contact administrator');
      } else {
        ElMessage.error(`Failed to get data: ${errorMsg}`);
      }
    } else if (error.request) {
      // The request was sent but no response was received
      ElMessage.error('No response from server, please check your network connection');
    } else {
      // The request could not be sent
      ElMessage.error(`Request error: ${error.message}`);
    }
  } finally {
    loading.value = false;
  }
}

// Get status style based on status value
const getStatusType = (status: string): 'primary' | 'success' | 'warning' | 'danger' | 'info' => {
  switch (status) {
    case 'Not Started': return 'primary';
    case 'In Progress': return 'warning';
    case 'Waiting for Review': return 'warning';
    case 'Completed': return 'success';
    case 'Pending Review': return 'warning';
    case 'Review Failed': return 'danger';
    default: return 'primary';
  }
};

onMounted(() => {
  // Get dashboard data when the page loads
  fetchDashboardData();
});
</script>
<style scoped>
.supervisor-dashboard {
  padding: 16px;
}

.dashboard-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.refresh-button {
  margin-left: auto;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.activity-item {
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.activity-item:hover {
  transform: translateY(-2px);
}

.activity-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.activity-description {
  color: #606266;
  font-size: 14px;
}

.activity-time {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
  text-align: right;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}
</style> 